<template>
    <div>
        <h1>Multiple Timers</h1>
        <div>
            <button type="button" @click="stoptimer1Scope">stoptimer1Scope</button>

            <button type="button" @click="stoptimer2Scope">stoptimer2Scope</button>

            <button type="button" @click="runtimer1Scope">runtimer1Scope</button>

            <button type="button" @click="runtimer2Scope">runtimer2Scope</button>

            <button type="button" @click="ganrao">干扰</button>
        </div>
        <div style="font-size: 30px" v-for="(item, index) in rac" :key="index">
            {{ item }}
        </div>
    </div>
</template>

<script setup>
import { ref, effectScope, onScopeDispose, reactive } from 'vue'

// 创建一个计时器的组合函数
function useTimer() {
    // 使用 effectScope 创建作用域
    const scope = effectScope()
    return scope
}

function srun(scope, step = 1000) {
    const time = ref(0)
    let interval

    scope.run(() => {
        // 开启计时器
        interval = setInterval(() => {
            console.log(time.value)

            time.value++
        }, step)

        // 在作用域销毁时清理定时器
        onScopeDispose(() => {
            clearInterval(interval)
            console.log('Timer stopped and resources cleaned up.')
        })
    })

    return { time }
}

let timer1 = useTimer()

console.log(timer1)

let rac = reactive([])

const runtimer1Scope = () => {
    let { time } = srun(timer1)
    rac.push(time)
}

const stoptimer1Scope = () => {
    timer1.stop()
}

let timer2 = useTimer()

const runtimer2Scope = () => {
    let { time } = srun(timer2)
    rac.push(time)
}

const stoptimer2Scope = () => {
    timer2.stop()
}

const ganrao = () => {
    rac[0].value = 20000
}

</script>
